import { app, BrowserWindow, dialog, ipcMain } from 'electron'
import path from 'node:path'

process.env.DIST = path.join(__dirname, '../dist')
process.env.PUBLIC = app.isPackaged ? process.env.DIST : path.join(process.env.DIST, '../public')
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
let win
const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']

function createWindow() {

  win = new BrowserWindow({
    width: 1366,
    height: 768,
    icon: path.join(__dirname, '../public/electron/icon-tool.png'),
    title: '\u200E',
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration:true,   //允许渲染进程使用node.js
      contextIsolation:false,  //允许渲染进程使用node.js
      webSecurity: false
    },
  })

  win.webContents.on('did-finish-load', () => {
    win.webContents.send('main-process-message', (new Date).toLocaleString())
  })

  const urlPath = '#/home'
  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL + urlPath)
  } else {
    win.loadFile(path.join(process.env.DIST, 'index.html'), {
      hash: 'home'
    })
  }

  if (!app.isPackaged) {
    win.webContents.openDevTools();
  }
}

app.on('window-all-closed', () => {
  win = null
})

app.whenReady().then(createWindow)

ipcMain.on('open-directory-dialog', () => {
  dialog.showOpenDialog({
    title: '选择文件夹',
    properties: ['openDirectory']
  }).then(res => {
    if (!res.canceled) {
      win.webContents.send('get-directory-dialog', res.filePaths[0]);
    }
  });
});

ipcMain.on('open-file-dialog', (event, obj = {}) => {
  dialog.showOpenDialog({
    title: '选择文件',
    properties: ['openFile'],
    ...obj,
  }).then(res => {
    if (!res.canceled) {
      win.webContents.send('get-file-dialog', res.filePaths);
    }
  });
});
